import { toNumber, isNull, has } from "lodash";
import Parameter from "./Parameter";
import { currentUser } from "../auth";

class NumberParameter extends Parameter {
  constructor(parameter, parentQueryId) {
    super(parameter, parentQueryId);
    this.setValue(parameter.value);
  }

  // eslint-disable-next-line class-methods-use-this
  normalizeValue(value, noneValuesOptions) {
    if (isNull(value) && !noneValuesOptions) {
      return null;
    }
    const normalizedValue = toNumber(value);
    return !isNaN(normalizedValue) ? normalizedValue : null;
  }

  fromUrlParams(query) {
    if (currentUser && this.name.indexOf("currentUser_") === 0) {
      const userProperty = this.name.substring(12);
      if (currentUser.hasOwnProperty(userProperty)) {
        this.setValue(currentUser[userProperty]);
        return;
      }
    }
    const prefix = this.urlPrefix;
    const key = `${prefix}${this.name}`;
    if (has(query, key)) {
      this.setValue(query[key]);
    }
  }
}

export default NumberParameter;
